import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'

import { asyncRoutes } from '@/router/dynamicRoute'
Vue.use(Router)

/* Layout */
import Layout from '@/layout'

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const NewArr = permsArr.map((item) => {
    return item.split(':')[0]
  })
  return [...new Set(NewArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return `${item.split(':')[0]}:${item.split(':')[1]}`
  })
  return [...new Set(newArr)]
}

// 根据权限标识过滤路由表
/** *
 * @param {*} firstRoutePerms ['park','parking',...]
 * @param {*} secondRoutePerms  ['park:building','parking:area',...]
 * @param {*} dinamicRoutes 动态路由规则表
 * @returns
 */
function getRoutes(firstRoutePerms, secondRoutePerms, dinamicRoutes) {
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  // return dinamicRoutes.filter(route => {
  //   return firstRoutePerms.includes(route.permission)
  // }).map(item => {
  //   // 2. 对二级路由做过滤
  //   return {
  //     ...item,
  //     children: item.children.filter(item => secondRoutePerms.includes(item.permission))
  //   }
  // })

  // 根据一级路由权限对动态路由表进行过滤,返回的是符合条件的路由，是路由数组
  const firstFilteredRoutes = dinamicRoutes.filter(item => {
    return firstRoutePerms.includes(item.permission)
  })

  // 对过滤后的一级路由的子路由进行二级路由权限过滤，item是一级路由数组中的每一条路由对象,最终返回值也是路由数组
  const secondFilteredRoutes = firstFilteredRoutes.map(item => {
    console.log(item)

    return {
      ...item,
      children: item.children.filter(() => {
        secondRoutePerms.includes(item.permission)
      })

    }
  })

  return secondFilteredRoutes
}

export const staticRoutes = [
  {
    path: '/login',
    component: () => import('@/views/Login/index'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/workbench'
  },
  {
    path: '/workbench',
    component: Layout,
    children: [{
      path: '',
      component: () => import('@/views/Workbench/index'),
      meta: { title: '工作台', icon: 'el-icon-data-board' }
    }]
  },

  // 添加月卡页面路由
  {
    path: '/cardAdd',
    component: () => import('@/views/Car/CarCard/cardAdd.vue')
  },
  // 编辑月卡页面路由
  {
    path: '/cardEdit',
    component: () => import('@/views/Car/CarCard/cardEdit.vue')
  },
  // 添加企业页面路由
  {
    path: '/enterpriseAdd',
    component: () => import('@/views/Park/Enterprise/exterpriseAdd.vue')
  },
  // 编辑企业
  {
    path: '/enterpriseEdit',
    component: () => import('../views/Park/Enterprise/enterpriseEdit.vue')

  },
  // 企业详情
  {
    path: '/enterpriseDetail',
    component: () => import('@/views/Park/Enterprise/exterpriseDetail.vue')
  },
  // 新增角色
  {
    path: '/roleAdd',
    component: () => import('@/views/System/Role/AddRole')
  },
  // 编辑角色
  {
    path: '/roleEdit',
    component: () => import('@/views/System/Role/EditRole')
  }
  // {
  //   path: '/404',
  //   component: () => import('@/views/404'),
  //   hidden: true
  // }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: staticRoutes
})

const router = createRouter()

// 重置路由方法
export function resetRouter() {
  // 得到一个全新的router实例对象
  const newRouter = createRouter()
  // 使用新的路由记录覆盖掉老的路由记录
  router.matcher = newRouter.matcher
}
// 全局前置路由

router.beforeEach(async(to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    const token = store.state.user.token

    if (token) {
      next()
      // 获取权限列表
      if (!store.state.user.profile.id) {
        const permissions = await store.dispatch('user/getProfile')
        // console.log('权限列表', permissions)
        // 处理一级和二级菜单标识
        // firstRoutePerms是总的一级路由权限
        const firstRoutePerms = getFirstRoutePerms(permissions)
        // console.log(firstRoutePerms)
        // secondRoutePerms是总的二级路由权限
        const secondRoutePerms = getSecondRoutePerms(permissions)
        // console.log(secondRoutePerms)
        // 根据权限标识过滤路由表
        const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
        if (permissions.includes('*:*:*')) {
          // 如果是管理员，就把所有的路由都添加到路由表中
          // 添加路由
          asyncRoutes.forEach(item => router.addRoute(item))
          store.commit('menu/setMenuList', asyncRoutes)
        } else {
          // 添加路由
          filterRoutes.forEach(item => router.addRoute(item))
          store.commit('menu/setMenuList', filterRoutes)
        }
        // 404这个组件是一个最后的路由规则，要放在最后兜底，否则会出现404组件闪动
        router.addRoute({
          path: '*',
          component: () => import('@/views/404'),
          hidden: true
        })
      }
    } else {
      // 跳转回登录页
      next('/login')
    }
  }
})

export default router
